﻿var mongojs = require('mongojs');
var excel = require('../domain/excel_helper.js');
var dateutils = require('./dateTools.js');
var crypt = require('../domain/mycrypt.js');
var database = require('../database/mongo_database.js');

var mail = require('nodemailer');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cp = require('child_process');
var Buffer = require('Buffer');

var jobs = database.jobs;
var users = database.users;
var settings = database.settings;
var departs = database.departs;
var excels = database.excels;
var update = database.update;


var version = '0.0.1';

exports.version = version;

exports.getAllExcels = function (req, res, next) {
    excels.find().limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.getNoSentExcels = function (req, res, next) {
    excels.find({ sent: '0' }).limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.getSentExcels = function (req, res, next) {
    excels.find({ sent: '1' }).limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}


exports.getUserNoSentExcels = function (req, res, next) {
    excels.find({ 'sent': '0' , 'user_id': req.params.user_id }).limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.getUserSentExcels = function (req, res, next) {
    excels.find({ 'sent': '1' , 'user_id': req.params.user_id }).limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.getUserNoSentExcelsByDate = function (req, res, next) {
    excels.find({ 'sent': '0' , 'user_id': req.params.user_id, 'date': req.params.date }).limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.getUserSentExcelsByDate = function (req, res, next) {
    excels.find({ 'sent': '1' , 'user_id': req.params.user_id, 'date': req.params.date }).limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.count_day_mailed = function (req, res, next) {
    excels.count({ 'sent': '1' , 'user_id': req.params.user_id, 'date': req.params.date }, function (err, success) {
        res.send(200, success);
    });
    return next();
}

exports.findSettingByName = function (req, res, next) {
    settings.findOne({ "name": req.params.name }, function (err, success) {
        if (success) {
            res.send(200, success.value);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.findAllSettings = function (req, res, next) {
    settings.find().limit(20).sort({ name: -1 }, function (err, success) {
        if (success) {
            res.send(200, success.value);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.findAllUsers = function (req, res, next) {
    users.find().limit(20).sort({ postedOn: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
};

exports.findUser = function (req, res, next) {
    users.findOne({ _id: mongojs.ObjectId(req.params.userId) }, function (err, success) {
        if (success) {
            success.mailpwd = crypt.decode(success.mailpwd, 'tsdykjhz');
            res.send(200, success);
            return next();
        } else {
            console.log(req.params.userId + " err");
            return next(err);
        }
    });
}

exports.findUserByUserId = function (req, res, next) {
    users.findOne({ id: req.params.userId }, function (err, success) {
        if (success) {
            success.mailpwd = crypt.decode(success.mailpwd, 'tsdykjhz');
            res.send(200, success);
            return next();
        } else {
            res.send(500, err);
            console.log(req.params.userId + " err");
            return next(err);
        }
    });
}


exports.deleteUser = function (req, res, next) {
    users.remove({ _id: mongojs.ObjectId(req.params.userId) }, function (err, success) {
        if (success) {
            res.send(201, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.saveUser = function (req, res, next) {
    var user = {};
    user.id = req.params.id;
    user.name = req.params.name;
    user.mail = req.params.mail;
    user.mailpwd = crypt.encode(req.params.mailpwd, 'tsdykjhz');
    user.mail2 = req.params.mail2;
    user.depart = req.params.depart;
    user.prefix_depart = req.params.prefix_depart;
    
    var oid = req.params.userId || "";
    
    if (oid) {
        var obj = { _id: mongojs.ObjectId(oid), id: user.id, name: user.name, mail: user.mail, mailpwd: user.mailpwd, mail2: user.mail2, depart : user.depart, prefix_depart: user.prefix_depart };
    }
    else {
        var obj = { id: user.id, name: user.name, mail: user.mail, mailpwd: user.mailpwd, mail2: user.mail2, depart : user.depart, prefix_depart: user.prefix_depart };
    }
    users.save(obj, function (err, success) {
        console.log('id is null');
        
        if (success) {
            res.send(205, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.updateJob = function (req, res, next) {
    
    var job = {};
    job.title = req.params.title;
    job.description = req.params.description;
    job.done_status = req.params.done_status;
    job.user_id = req.params.user_id;
    job.build = "0";
    job.date = req.params.date;
    
    jobs.update({ _id: mongojs.ObjectId(req.params.jobId) }, {
        title: job.title, 
        description: job.description, 
        done_status: job.done_status, 
        user_id: job.user_id, 
        build : job.build,
        date: job.date
    }, function (err, success) {
        if (success) {
            res.send(205, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.findBuildJobs = function (req, res, next) {
    
    jobs.find({
        user_id: req.params.userid, 
        build: "1",
        date: req.params.date
    }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.findNoBuildJobs = function (req, res, next) {
    jobs.find({
        user_id: req.params.userid,
        build: "0",
        date: req.params.date
        
    }, function (err, success) {
        
        
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}


exports.findAllJobs = function (req, res, next) {
    jobs.find().limit(20).sort({ date: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.findJob = function (req, res, next) {
    jobs.findOne({ _id: mongojs.ObjectId(req.params.jobId) }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.postNewJob = function (req, res, next) {
    var job = {};
    job.title = req.params.title;
    job.description = req.params.description;
    job.done_status = req.params.done_status;
    job.user_id = req.params.user_id;
    job.build = "0";
    job.date = req.params.date;
    
    jobs.save(job, function (err, success) {
        console.log('Response success ' + success);
        console.log('Response error ' + err);
        if (success) {
            res.send(201, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.deleteJob = function (req, res, next) {
    jobs.remove({ _id: mongojs.ObjectId(req.params.jobId) }, function (err, success) {
        console.log('Response success ' + success);
        console.log('Response error ' + err);
        if (success) {
            res.send(204, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.findAllDeparts = function (req, res, next) {
    departs.find().limit(20).sort({ id: -1 }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}
exports.findDepart = function (req, res, next) {
    departs.findOne({ id: req.params.id }, function (err, success) {
        if (success) {
            res.send(200, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.postNewDepart = function (req, res, next) {
    
    var depart = {}
    depart.id = req.params.id;
    depart.flag = req.params.flag;
    depart.name = req.params.name;
    departs.save(depart, function (err, success) {
        console.log('Response success ' + success);
        console.log('Response error ' + err);
        if (success) {
            res.send(201, success);
            return next();
        } else {
            return next(err);
        }
        
    });
}

exports.deleteDepart = function (req, res, next) {
    departs.remove({ id: req.params.id }, function (err, success) {
        console.log('Response success ' + success);
        console.log('Response error ' + err);
        if (success) {
            res.send(204, success);
            return next();
        } else {
            return next(err);
        }
    });
}
exports.updateDepart = function (req, res, next) {
    
    var depart = {}
    depart.id = req.params.id;
    depart.flag = req.params.flag;
    depart.name = req.params.name;
    
    departs.update({ id: req.params.id }, {
        id: depart.id, name: depart.name, flag: depart.flag
    }, function (err, success) {
        if (success) {
            res.send(205, success);
            return next();
        } else {
            return next(err);
        }
    });
}

exports.do_excel = function (req, res, next) {
    console.log(Date() + ' EXCEL MAIL SENDING: ' + req.params.user_id);
    
    function mail_exec(zk_mail_str) {
        settings.findOne({ 'name': 'excel_generater_path' }, function (err, exepath) {
            if (exepath) {
                var exefile = exepath.value;
                if (fs.existsSync(exefile)) {
                    var line = exefile + " " + req.params.user_id + " " + req.params.date;
                    var cmd = cp.exec(line);
                    
                    cmd.stdout.on('data', function (data) {
                        console.log('stdout: ' + data);
                    });
                    
                    cmd.stderr.on('data', function (data) {
                        console.log('stderr: ' + data);
                        res.send(207, 'exe run error');
                    });
                    
                    cmd.on('exit', function (code) {
                        if (code == 0) {
                            
                            users.findOne({ id: req.params.user_id }, function (error, success) {
                                if (success) {
                                    excels.findOne({ 'user_id': req.params.user_id, 'sent': '0', date : req.params.date }, function (err, found) {
                                        if (found) {
                                            try {
                                                
                                                var excelfile = found.filepath;
                                                console.log(Date() + " Excel file path: ", excelfile);
                                                
                                                var transporter = mail.createTransport({
                                                    service: 'QQ',
                                                    auth: {
                                                        user: success.mail,
                                                        pass: crypt.decode(success.mailpwd, 'tsdykjhz')
                                                    }
                                                });
                                                
                                                var mailoptions = {
                                                    from: { name: success.name, address: success.mail },
                                                    to: zk_mail_str + "," + success.mail2 + "," + success.mail,
                                                    subject: success.name + ' ' + path.basename(excelfile),
                                                    html: '<b> 达意科技工作日志 by ' + success.name + "</b>",
                                                    attachments: [{ filename: path.basename(excelfile), path: excelfile }]
                                                }
                                                
                                                transporter.sendMail(mailoptions, function (error1, info) {
                                                    
                                                    if (error1) {
                                                        console.log(error1);
                                                        res.send(207, 'mail error');
                                                    } else {
                                                        //更新数据库
                                                        console.log(Date() + " Updating database:" + found.filepath);
                                                        found.sent = "1"
                                                        excels.save(found);
                                                        res.send(200, 'mail sent')
                                                        console.log(Date() + ' Message sent: ' + info.response);
                                                    }
                                                });
                    
                                            } catch (e) {
                                                res.send(207, 'mail error');
                                                console.log(e);
                                            }
                                        } else {
                                            res.send(208, 'no record in excels table');
                                        }
                                    });
                                } else {
                                    res.send(209, 'no record in user table');
                                }
                            });
           
                        } else {
                            res.send(206, "mail error");
                        }
                    });

                }
                else {
                    res.send(207, 'exe file does not exists');
                }

            } else {
                res.send(208, 'no data in settings table');
            }
        });
    }
    
    
    settings.findOne({ 'name': 'zk_mail' }, function (e0, zk_mail_data) {
        
        if (zk_mail_data) {
            mail_exec(zk_mail_data.value);
        } else {
            res.send(208, 'can not get zk_mail from settings');
        }
        
    });
    

}

//exports.do_excel = function (req, res, next) {

//    excel.do_excel(req, res, next);
//}

exports.test = function (req, res, next) {
    res.send(200, "ok");
    return next();
}


exports.uploadapk = function (req, res, next) {
    var upname = req.files.newapk.path;
    var new_filename = path.join(path.dirname(upname), req.files.newapk.name);
    fs.rename(upname, new_filename, function (error) {
        if (error) {
            console.log();
            res.send(500, error);
        }
        update.remove();
        
        update.insert({
            'filepath': new_filename, 'version': req.body.version, 
            'description': req.body.desc , 'date': Date()
        }, function (error, success) {
            console.log(success);
            console.log(error);
            if (success) {
                res.send(200, success);
            } else {
                res.send(500, error);
            }
        });
        return next();

    });

   
}
exports.getApk = function (req, res, next) {
    
    update.findOne({}, function (error, success) {
        console.log(success);
        console.log(error);
        if (success) {
            var file = success.filepath;
            var mimetype = mime.lookup(file);
            
            var f = fs.readFileSync(file, 'binary');
            
            res.setHeader('Content-Length', f.length);
            res.setHeader('Content-disposition', 'attachment; filename=' + file);
            res.setHeader('Content-type', mimetype);
            
            var filestream = fs.createReadStream(file);
            filestream.pipe(res);
        } else {
            res.send(500, error);
        }

    })
    next();
}

exports.updateCheck = function (req, res, next) {
    
    update.findOne({}, function (error, success) {
        console.log(success);
        console.log(error);
        if (success) {
            res.send(200, success);
        } else {
            res.send(500, error);
        }

    })
    next();

}

exports.about = function (req, res, next) {
    
    fs.readFile('./about/about.html', 'utf8', function (err, data) {
        
        if (err) {
            console.log(err);
            throw err;
        }
        
        var body = data;
        res.writeHead(200, {
            'Content-Length': Buffer.byteLength(body),
            'Content-Type': 'text/html'
        });
        res.write(body);
        res.end();
        next();
    })
}

function exec_py() {
    var pyscript = './scripts/toadyCalendar.py';
    var line = "c:/python27/python.exe " + pyscript;
    var cmd = cp.exec(line);

    cmd.stdout.on('data', function (data) {
        console.log('stdout: ', data);
    });
    
    cmd.stderr.on('data', function (data) {
        console.log('stderr: ', data);

        if (data == 'success') {
            console.log('EXEC_PY', 'python script execute successed');
        }
        else {
            console.log('EXEC_PY', 'python script execute failed');
        }

    });
    
    cmd.on('exit', function (code) {
        if (code == 0) {
            console.log('cmd successed');
        }
        else {
            console.log('cmd error exit');
        }
    });
}

exports.newDiary = function (req, res, next) {

    fs.readFile('index.html', 'utf8', function (err, data) {

        if (err) {
            console.log(err);
            throw err;
        }

        var body = data;
        res.writeHead(200, {
            'Content-Length': Buffer.byteLength(body),
            'Content-Type': 'text/html'
        });
        res.write(body);
        res.end();
        next();
    })
};

exports.downloadExcelFile = function(req, res, next){

    excels.findOne({_id: mongojs.ObjectId(req.params.id)}, function (error, success) {
        if (success) {

            var file = success.filepath;
            var mimetype = mime.lookup(file);

            var f = fs.readFileSync(file, 'binary');

            res.setHeader('Content-Length', f.length);
            res.setHeader('Content-disposition', 'attachment; filename=' + file);
            res.setHeader('Content-type', mimetype);

            var filestream = fs.createReadStream(file);
            filestream.pipe(res);
        } else {
            res.send(500, error);
        }

    })
    next();

};